package com.quasar.hpatient.view.community;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.model.medicalmodel.CommunityData;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.presenter.CirclePresenter;
import com.quasar.hpatient.utils.UrlUtils;
import com.quasar.hpatient.view.MainActivity;
import com.quasar.hpatient.view.adapter.BaseRecycleViewAdapter;
import com.quasar.hpatient.view.community.bean.ActionItem;
import com.quasar.hpatient.view.community.bean.PhotoInfo;
import com.quasar.hpatient.view.community.viewhoder.CircleViewHolder;
import com.quasar.hpatient.view.community.viewhoder.ImageViewHolder;
import com.vise.log.ViseLog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yiwei on 16/5/17.
 */
public class CircleAdapter extends BaseRecycleViewAdapter {

    public final static int TYPE_HEAD = 0;

    private static final int STATE_IDLE = 0;
    public static final int HEADVIEW_SIZE = 1;

    public final static int TYPE_URL = 1;
    public final static int TYPE_IMAGE = 2;

    //获取当前用户信息
    PatientInfoData patientInfoData = MainAppliaction.getInstance().getPatient();

    int curPlayIndex = -1;

    private CirclePresenter presenter;
    private Context context;

    public void setCirclePresenter(CirclePresenter presenter) {
        this.presenter = presenter;
    }

    public CircleAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_HEAD;
        }

        int itemType = 0;
        CommunityData item = (CommunityData) datas.get(position - 1);
        if (CommunityData.TYPE_URL.equals(item.type())) {
            itemType = CircleAdapter.TYPE_URL;
        } else if (CommunityData.TYPE_IMG.equals(item.type())) {
            itemType = CircleAdapter.TYPE_IMAGE;
        }
        return 2;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;


        ViseLog.d("显示的布局" + viewType);

        if (viewType == TYPE_HEAD) {
            View headView = LayoutInflater.from(parent.getContext()).inflate(R.layout.head_circle, parent, false);
            viewHolder = new HeaderViewHolder(headView);

            ImageView icon_head = (ImageView) headView.findViewById(R.id.imageview_avator);
            Glide.with(context).load(RetrofitConnection.PHOTOURL + patientInfoData.getCover()).
                    diskCacheStrategy(DiskCacheStrategy.ALL).
                    placeholder(R.color.bg_no_photo).transform(new GlideCircleTransform(context)).into(icon_head);

            TextView tv_user_name = (TextView) headView.findViewById(R.id.tv_user_name);
            tv_user_name.setText(patientInfoData.getNick());
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_circle_item, parent, false);

            if (viewType == CircleViewHolder.TYPE_URL) {
                viewHolder = new URLViewHolder(view);
            } else if (viewType == CircleViewHolder.TYPE_IMAGE) {
                viewHolder = new ImageViewHolder(view);
            }
        }

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) {

        if (getItemViewType(position) == TYPE_HEAD) {
            //HeaderViewHolder holder = (HeaderViewHolder) viewHolder;
        } else {

            final int circlePosition = position - HEADVIEW_SIZE;
            final CircleViewHolder holder = (CircleViewHolder) viewHolder;
            final CommunityData communityData = (CommunityData) datas.get(circlePosition);


            ViseLog.d("对象" + communityData);
            //帖子id
            final String circleId = communityData.getId() + "";
            //发帖人姓名
            String name = "";
            //发帖人头像
            String headImg = "";
            if (communityData.getPatientInfo() != null) {
                name = communityData.getPatientInfo().getRealName();
                headImg = communityData.getPatientInfo().getCover();
            }

            //发帖内容
            final String content = communityData.getContent();
            //发帖时间
            String createTime = communityData.getUpTime();
            //点赞
            final List<CommunityData.ListPraiseBean> favortDatas = communityData.getListPraise();
            //评论
            final List<CommunityData.ListCommentBean> commentsDatas = communityData.getListComment();
            boolean hasFavort = communityData.hasFavort();
            boolean hasComment = communityData.hasComment();

            Glide.with(context).load(RetrofitConnection.PHOTOURL + headImg).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.color.bg_no_photo).transform(new GlideCircleTransform(context)).into(holder.headIv);
            holder.nameTv.setText(name);
            holder.timeTv.setText(createTime);

            if (!TextUtils.isEmpty(content)) {
                holder.contentTv.setExpand(communityData.isExpand());
                holder.contentTv.setExpandStatusListener(new ExpandTextView.ExpandStatusListener() {
                    @Override
                    public void statusChange(boolean isExpand) {
                        communityData.setExpand(isExpand);
                    }
                });

                holder.contentTv.setText(UrlUtils.formatUrlString(content));
            }
            holder.contentTv.setVisibility(TextUtils.isEmpty(content) ? View.GONE : View.VISIBLE);

            //DatasUtil.curUser.getId()

            //如果自己的id和返回的发帖信息里面的id相等则显示删除按钮
            if (communityData.getPatientInfo() != null) {
                if (patientInfoData.getId() == communityData.getPatientInfo().getId()) {
                   // holder.deleteBtn.setVisibility(View.VISIBLE); 暂时取消删除按钮功能
                    holder.deleteBtn.setVisibility(View.GONE);
                } else {
                    holder.deleteBtn.setVisibility(View.GONE);
                }
                holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //删除
                        if (presenter != null) {
                            presenter.deleteCircle(circleId);
                        }
                    }
                });
            }

            if (hasFavort || hasComment) {
                if (hasFavort) {//处理点赞列表
                    holder.praiseListView.setOnItemClickListener(new PraiseListView.OnItemClickListener() {
                        @Override
                        public void onClick(int position) {
                            String userName = favortDatas.get(position).getName();
                            String userId = favortDatas.get(position).getId() + "";
                            Toast.makeText(MainAppliaction.getInstance(), userName + " &id = " + userId, Toast.LENGTH_SHORT).show();
                        }
                    });
                    holder.praiseListView.setDatas(favortDatas);
                    holder.praiseListView.setVisibility(View.VISIBLE);
                } else {
                    holder.praiseListView.setVisibility(View.GONE);
                }

                if (hasComment) {//处理评论列表
                    holder.commentList.setOnItemClickListener(new CommentListView.OnItemClickListener() {
                        @Override
                        public void onItemClick(int commentPosition) {
                            CommunityData.ListCommentBean commentItem = commentsDatas.get(commentPosition);
                            //DatasUtil.curUser.getId()
                            if (patientInfoData.getId() == commentItem.getUserId()) {//复制或者删除自己的评论

                                ViseLog.d("评论列表" + commentItem.getComment());

                                CommentDialog dialog = new CommentDialog(context, presenter, commentItem, circlePosition);
                                dialog.show();
                            }
//                            else {//回复别人的评论
//                                if (presenter != null) {
//                                    CommunityData.ListCommentBean config = new CommunityData.ListCommentBean();
//                                    config.circlePosition = circlePosition;
//                                    config.commentPosition = commentPosition;
//                                    config.commentType = CommentConfig.Type.REPLY;
//                                    presenter.showEditTextBody(config);
//                                }
//                            }
                        }
                    });
                    holder.commentList.setDatas(commentsDatas);
                    holder.commentList.setVisibility(View.VISIBLE);

                } else {
                    holder.commentList.setVisibility(View.GONE);
                }
                holder.digCommentBody.setVisibility(View.VISIBLE);
            } else {
                holder.digCommentBody.setVisibility(View.GONE);
            }

            holder.digLine.setVisibility(hasFavort && hasComment ? View.VISIBLE : View.GONE);

            final SnsPopupWindow snsPopupWindow = holder.snsPopupWindow;
            //判断是否已点赞
            String curUserFavortId = communityData.getListPraise() + "";
//            if(!TextUtils.isEmpty(curUserFavortId)){
//                snsPopupWindow.getmActionItems().get(0).mTitle = "取消";
//            }else{
//                snsPopupWindow.getmActionItems().get(0).mTitle = "赞";
//            }

            if (favortDatas.size() != 0) {

                for (int i = 0; i < favortDatas.size(); i++) {

                    if (favortDatas != null) {
                        if (favortDatas.get(i) != null) {
                            if (favortDatas.get(i).getId() == patientInfoData.getId()) {
                                snsPopupWindow.getmActionItems().get(0).mTitle = "取消";
                            } else {
                                snsPopupWindow.getmActionItems().get(0).mTitle = "赞";
                            }
                        }
                    }
                }
            } else {
                snsPopupWindow.getmActionItems().get(0).mTitle = "赞";
            }

            snsPopupWindow.update();
            snsPopupWindow.setmItemClickListener(new PopupItemClickListener(circlePosition, communityData, curUserFavortId));
            holder.snsBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //弹出popupwindow
                    snsPopupWindow.showPopupWindow(view);
                }
            });

            holder.urlTipTv.setVisibility(View.GONE);
            switch (holder.viewType) {
//                case CircleViewHolder.TYPE_URL:// 处理链接动态的链接内容和和图片
//                    if(holder instanceof URLViewHolder){
//                        String linkImg = circleItem.getLinkImg();
//                        String linkTitle = circleItem.getLinkTitle();
//                        Glide.with(context).load(linkImg).into(((URLViewHolder)holder).urlImageIv);
//                        ((URLViewHolder)holder).urlContentTv.setText(linkTitle);
//                        ((URLViewHolder)holder).urlBody.setVisibility(View.VISIBLE);
//                        ((URLViewHolder)holder).urlTipTv.setVisibility(View.VISIBLE);
//                    }
//
//                    break;
                case CircleViewHolder.TYPE_IMAGE:// 处理图片
                    if (holder instanceof ImageViewHolder) {
                        final ArrayList<PhotoInfo> pms = new ArrayList<>();

                        //显示图片
                        if (communityData.getCover() != null) {
                            String[] aa = communityData.getCover().split(",");

                            for (int i = 0; i < aa.length; i++) {
                                PhotoInfo photoInfo = new PhotoInfo();
                                photoInfo.url = RetrofitConnection.PHOTOURL + aa[i];
                                pms.add(photoInfo);
                            }
                        }

                        if (pms != null && pms.size() > 0) {
                            ((ImageViewHolder) holder).multiImageView.setVisibility(View.VISIBLE);
                            ((ImageViewHolder) holder).multiImageView.setList(pms);
                            ((ImageViewHolder) holder).multiImageView.setOnItemClickListener(new MultiImageView.OnItemClickListener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    //imagesize是作为loading时的图片size
                                    ImagePagerActivity.ImageSize imageSize = new ImagePagerActivity.ImageSize(view.getMeasuredWidth(), view.getMeasuredHeight());

                                    List<String> photoUrls = new ArrayList<String>();
                                    for (PhotoInfo photoInfo : pms) {
                                        photoUrls.add(photoInfo.url);
                                    }
                                    ImagePagerActivity.startImagePagerActivity(((MainActivity) context), photoUrls, position, imageSize);


                                }
                            });
                        } else {
                            ((ImageViewHolder) holder).multiImageView.setVisibility(View.GONE);
                        }
                    }

                    break;
            }
        }
    }

    @Override
    public int getItemCount() {
        return datas.size() + 1;//有head需要加1
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
    }

    public class HeaderViewHolder extends RecyclerView.ViewHolder {

        public HeaderViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class PopupItemClickListener implements SnsPopupWindow.OnItemClickListener {
        private String mFavorId;
        //动态在列表中的位置
        private int mCirclePosition;
        private long mLasttime = 0;
        private CommunityData mCircleItem;

        public PopupItemClickListener(int circlePosition, CommunityData circleItem, String favorId) {
            this.mFavorId = favorId;
            this.mCirclePosition = circlePosition;
            this.mCircleItem = circleItem;
        }

        @Override
        public void onItemClick(ActionItem actionitem, int position) {
            switch (position) {
                case 0://点赞、取消点赞
                    if (System.currentTimeMillis() - mLasttime < 700)//防止快速点击操作
                        return;
                    mLasttime = System.currentTimeMillis();
                    if (presenter != null) {
                        if ("赞".equals(actionitem.mTitle.toString())) {
                            presenter.addFavort(mCirclePosition);
                        } else {//取消点赞
                            presenter.deleteFavort(mCirclePosition, mFavorId);
                        }
                    }
                    break;
                case 1://发布评论
                    if (presenter != null) {
                        CommunityData.ListCommentBean config = new CommunityData.ListCommentBean();
                        config.setNoteId(mCirclePosition);
                        config.setPostId(mCircleItem.getId() + "");//记录帖子id
                        presenter.showEditTextBody(config);
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
